package com.lmaor.project.commons.bytes;

public class ByteIndexUtils {
	public static int indexOf(byte[] bytes,byte[] sh,int startIndex) {
		int shIndex = 0;
		int i = startIndex;
		int shLength = sh.length;
		int bytesLength = bytes.length;
		for ( ;i < bytesLength && shIndex < shLength; i++) {
			if(bytes[i] == sh[shIndex]) {
				shIndex++;
			}else if(bytes[i]==sh[0]){
				shIndex = 1;
			}else {
				shIndex = 0;
			}
		}
		if(shIndex == shLength) {
			return i-shLength;
		}else {
			return -1;
		}
	}
	
	public static boolean equals(byte[] bs1,byte[] bs2) {
		if(bs1 == bs2) {
			return true;
		}
		if(bs1==null||bs2==null||bs1.length != bs2.length) {
			return false;
		}
		int index = bs2.length - 1;
		while(index>=0) {
			if(bs1[index]!=bs2[index]) {
				return false;
			}else {
				index --;
			}
		}
		return true;
	} 
	/** 比较 数组bs1从 startIndex 到 endIndex 与传入数组bs2是否完全相等
	 * 
	 * @param bs1
	 * @param startIndex
	 * @param endIndex
	 * @param bs2
	 * @return
	 */
	public static boolean equals(byte[] bs1,int startIndex,int endIndex,byte[] bs2) {
		int length = endIndex - startIndex;
		if(bs2 == null || length != bs2.length) {
			return false;
		}
		int index1 = endIndex - 1;
		int index2 = bs2.length - 1;
		
		while(index2>=0) {
			if(bs1[index1]!=bs2[index2]) {
				return false;
			}else {
				index2 --;
				index1 --;
			}
		}
		return true;
	} 
	
}
